// 随访记录页面
const auth = require('../../utils/auth.js');
// 统一：弃用 config.baseUrl，改用 app.globalData.apiBaseUrl + 实体端点 followup_records
// const config = require('../../utils/config');
const moment = require('../../utils/moment');

Page({
  data: {
    userInfo: {},
    studentId: null,
    loading: true,
    followups: [],
    currentPage: 1,
    hasMore: true,
    loadingMore: false,
    
    // 筛选条件
    statusFilter: 'all', // all, pending, completed, overdue
    
    // 统计信息
    statistics: {
      total: 0,
      pending: 0,
      completed: 0,
      overdue: 0
    }
  },

  onLoad: function() {
    this.loadUserInfo();
    this.loadFollowups();
  },

  onPullDownRefresh: function() {
    this.setData({
      currentPage: 1,
      followups: [],
      hasMore: true
    });
    this.loadStatistics();
    this.loadFollowups();
  },

  onReachBottom: function() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.loadMoreFollowups();
    }
  },

  // 加载用户信息
  loadUserInfo: function() {
    const userInfo = auth.getCurrentUser && auth.getCurrentUser();
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        studentId: userInfo.student_id || userInfo.education_id || null,
        loading: false
      });
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载统计信息
  loadStatistics: function() {
    const total = this.data.followups.length;
    // 对于历史随访记录，我们按类型来统计而不是按状态
    const regular = this.data.followups.filter(f => f.followup_type === '定期随访').length;
    const special = this.data.followups.filter(f => f.followup_type === '专项随访').length;
    const satisfaction = this.data.followups.filter(f => f.followup_type === '满意度调查').length;
    this.setData({
      statistics: { 
        total, 
        pending: regular,    // 显示定期随访数量
        completed: special,  // 显示专项随访数量  
        overdue: satisfaction // 显示满意度调查数量
      }
    });
  },

  // 加载随访记录列表
  loadFollowups: function() {
    this.setData({ loading: true });
    wx.request({
      url: `${getApp().globalData.apiBaseUrl}/followup_records/list`,
      method: 'GET',
      header: { 'Authorization': `Bearer ${auth.getToken()}` },
      data: {
        student_id: this.data.studentId || '',
        page: this.data.currentPage,
        limit: 20
      },
      success: (res) => {
        wx.stopPullDownRefresh();
        this.setData({ loading: false });
        if (res.statusCode === 200) {
          // 结构兼容: 旧结构 data.followups / 新结构 records / 直接数组
            const payload = res.data.data || res.data;
            let list = payload.followups || payload.records || payload.list || [];
            
            // 前端筛选逻辑
            if (this.data.statusFilter !== 'all') {
              const filterMap = {
                'pending': '定期随访',
                'completed': '专项随访', 
                'overdue': '满意度调查'
              };
              const targetType = filterMap[this.data.statusFilter];
              if (targetType) {
                list = list.filter(item => item.followup_type === targetType);
              }
            }
            
            this.setData({
              followups: this.data.currentPage === 1 ? list : [...this.data.followups, ...list],
              hasMore: list.length === 20,
              currentPage: this.data.currentPage
            });
            this.loadStatistics();
        } else {
          wx.showToast({ title: res.data.message || '加载失败', icon: 'none' });
        }
      },
      fail: (error) => {
        wx.stopPullDownRefresh();
        this.setData({ loading: false });
        console.error('加载随访记录失败:', error);
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 加载更多随访记录
  loadMoreFollowups: function() {
    this.setData({ 
      loadingMore: true,
      currentPage: this.data.currentPage + 1
    });
    wx.request({
      url: `${getApp().globalData.apiBaseUrl}/followup_records/list`,
      method: 'GET',
      header: { 'Authorization': `Bearer ${auth.getToken()}` },
      data: {
        student_id: this.data.studentId || '',
        page: this.data.currentPage,
        limit: 20,
        status: this.data.statusFilter
      },
      success: (res) => {
        this.setData({ loadingMore: false });
        if (res.statusCode === 200) {
          const payload = res.data.data || res.data;
          const newFollowups = payload.followups || payload.records || payload.list || [];
          this.setData({
            followups: [...this.data.followups, ...newFollowups],
            hasMore: newFollowups.length === 20
          });
          this.loadStatistics();
        }
      },
      fail: (error) => {
        this.setData({ loadingMore: false });
        console.error('加载更多随访记录失败:', error);
      }
    });
  },

  // 切换状态筛选
  onStatusFilterChange: function(e) {
    const status = e.currentTarget.dataset.status;
    if (status !== this.data.statusFilter) {
      this.setData({
        statusFilter: status,
        currentPage: 1,
        followups: [],
        hasMore: true
      });
      this.loadFollowups();
    }
  },

  // 查看随访详情
  viewFollowupDetail: function(e) {
    const followup = e.currentTarget.dataset.followup;
    wx.navigateTo({
      url: `/pages/followup/detail/detail?id=${followup.id}`
    });
  },

  // 完成随访
  completeFollowup: function(e) {
    e.stopPropagation();
    const followup = e.currentTarget.dataset.followup;
    
    wx.showModal({
      title: '确认完成',
      content: '确定标记此随访为已完成吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateFollowupStatus(followup.id, 'completed');
        }
      }
    });
  },

  // 更新随访状态
  updateFollowupStatus: function(followupId, status) {
    wx.request({
      url: `${getApp().globalData.apiBaseUrl}/followup_records/${followupId}`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${auth.getToken()}`,
        'Content-Type': 'application/json'
      },
      data: {
        status: status // 真实后端如果无此字段更新需后续调整
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '状态更新成功',
            icon: 'success'
          });
          this.loadStatistics();
          this.loadFollowups();
        } else {
          wx.showToast({
            title: res.data.message || '更新失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        console.error('更新随访状态失败:', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 格式化日期
  formatDate: function(dateString) {
    return moment(dateString).format('YYYY-MM-DD');
  },

  // 格式化时间
  formatDateTime: function(dateString) {
    return moment(dateString).format('MM-DD HH:mm');
  },

  // 获取状态文本
  getStatusText: function(status) {
    const statusMap = {
      'pending': '待随访',
      'completed': '已完成',
      'overdue': '已逾期'
    };
    return statusMap[status] || '未知状态';
  },

  // 获取状态样式类
  getStatusClass: function(status) {
    const classMap = {
      'pending': 'pending',
      'completed': 'completed',
      'overdue': 'overdue'
    };
    return classMap[status] || 'pending';
  },

  // 获取优先级图标
  getPriorityIcon: function(priority) {
    const iconMap = {
      'high': '🔴',
      'medium': '🟡',
      'low': '🟢'
    };
    return iconMap[priority] || '🟢';
  }
});
